package dao;

import java.util.List;

import hibernate.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import entity.DArea;
import entity.DCentral;
import entity.DSucursal;
import entity.Deposito;


public class DepositoDAO {

	private static DepositoDAO instancia = null;
	private static SessionFactory sf = null;
	
	private DepositoDAO(){
		sf = HibernateUtil.getSessionFactory();
	}
	
	public static DepositoDAO getInstancia(){
		if(instancia == null)
			instancia = new DepositoDAO();
		return instancia;
	}

	public DCentral getDepositoCentral() {
		
		Session s = null;
		DCentral d = null;
		
		try{
			s = sf.getCurrentSession();
			Transaction t = s.beginTransaction();
			
			d = (DCentral) s.createQuery("from DCentral").uniqueResult();
			t.commit();
			
		}catch(Exception e){
			System.out.println(e);
			System.out.println("ErrorDAO: DepositoDAO.getDepositoCentral");
		}
		
		return d;
		
	}

	public void merge(Deposito deposito) {
			Transaction t = null;
		
			Session s = sf.getCurrentSession();
			
			try {
				t = s.beginTransaction();
				s.merge(deposito);
				s.flush();
				t.commit();
			
			} catch (Exception e) {
				t.rollback();
				System.out.println(e);
				System.out.println("ErrorDAO: MergeDeposito");
			}
		
		
	}

	public DSucursal getDepositoSucursal(int idDeposito) {
		Session s = null;
		DSucursal d = null;
		
		try{
			s = sf.getCurrentSession();
			Transaction t = s.beginTransaction();
			
			Query q = s.createQuery("select d from DSucursal d where d.idDeposito = :identificador");
			q.setParameter("identificador", idDeposito);
			d = (DSucursal) q.uniqueResult();
			t.commit();
			
		}catch(Exception e){
			System.out.println(e);
			System.out.println("ErrorDAO: DepositoDAO.getDepositoSucursal");
		}
		
		return d;
	}

	public DArea getDepositoArea(int idDeposito) {
		Session s = null;
		DArea d = null;
		
		try{
			s = sf.getCurrentSession();
			Transaction t = s.beginTransaction();
			
			Query q = s.createQuery("select d from DArea d where d.idDeposito = :identificador");
			q.setParameter("identificador", idDeposito);
			d = (DArea) q.uniqueResult();
			t.commit();
			
		}catch(Exception e){
			System.out.println(e);
			System.out.println("ErrorDAO: DepositoDAO.getDepositoArea");
		}
		
		return d;
	}

	
}